package org.jeecg.modules.staff.fault.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import me.zhyd.oauth.utils.StringUtils;
import me.zhyd.oauth.utils.UuidUtils;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.modules.bicycle.vehicle.entity.BikeVehicle;
import org.jeecg.modules.bicycle.vehicle.mapper.BikeVehicleMapper;
import org.jeecg.modules.constant.BikeConstant;
import org.jeecg.modules.param.fault.entity.BikeFaultSubmit;
import org.jeecg.modules.param.fault.entity.BikeFaultSubmitFile;
import org.jeecg.modules.param.fault.mapper.BikeFaultSubmitFileMapper;
import org.jeecg.modules.param.fault.mapper.BikeFaultSubmitMapper;
import org.jeecg.modules.param.fault.vo.FaultRes;
import org.jeecg.modules.param.pile.entity.BikePile;
import org.jeecg.modules.param.pile.mapper.BikePileMapper;
import org.jeecg.modules.param.staffUser.entity.LoginRes;
import org.jeecg.modules.param.staffUser.mapper.StaffMapper;
import org.jeecg.modules.param.station.entity.BikeStation;
import org.jeecg.modules.param.station.mapper.BikeStationMapper;
import org.jeecg.modules.staff.fault.service.StaffFaultService;
import org.jeecg.modules.system.announcement.service.IBikeAnnouncementService;
import org.jeecg.modules.user.abnormal.dto.FaultReq;
import org.jeecg.modules.utils.BikeResult;
import org.jeecg.modules.utils.RandomCodeUtils;
import org.jeecg.modules.utils.YueYueNiaoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.beans.Transient;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

@Service
public class StaffFaultServiceImpl implements StaffFaultService {

    @Autowired
    private StaffMapper staffMapper;
    @Autowired
    private BikeFaultSubmitMapper bikeFaultSubmitMapper;
    @Autowired
    private BikeVehicleMapper bikeVehicleMapper;
    @Autowired
    private BikeStationMapper bikeStationMapper;
    @Autowired
    private BikePileMapper bikePileMapper;
    @Autowired
    private BikeFaultSubmitFileMapper bikeFaultSubmitFileMapper;
    @Autowired
    private IBikeAnnouncementService bikeAnnouncementService;
    @Value("${application.domain}")
    public String domain;

    public String getDomain() {
        return domain;
    }

    public void setDomain(String domain) {
        this.domain = domain;
    }


    @Transient
    @Override
    public BikeResult insertStaffFault(FaultReq faultReq, HttpServletRequest request) {
        if (StringUtils.isEmpty(faultReq.getPileCode())) {
            return BikeResult.error("0", "请填写车桩号", null);
        }
        if (faultReq.getPileCode().length() != 11) {
            return BikeResult.error("0", "车桩编号有误", null);
        }
        String accessToken = request.getHeader("X-Access-Token");
        // 解密获得username，用于和数据库进行对比
        String username = JwtUtil.getUsername(accessToken);
        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("username",username);
        LoginRes loginRes = staffMapper.selectOne(queryWrapper1);
        SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMddHHmmssSSS");

        BikeFaultSubmit bikeFaultSubmit = new BikeFaultSubmit();

        //新增上报故障记录
        String uuid = YueYueNiaoUtils.getUUid();

        QueryWrapper queryWrapper2 = new QueryWrapper();
        queryWrapper2.eq("name",faultReq.getStationName());
        BikeStation bikeStation = bikeStationMapper.selectOne(queryWrapper2);
        if (bikeStation==null){
            return BikeResult.error("0","无该网点",null);
        }
        if (StringUtils.isNotEmpty(faultReq.getPileCode())){
            if (!bikeStation.getCode().equals(faultReq.getPileCode().substring(0,5))){
                return BikeResult.error("0","车桩与网点不匹配",null);
            }
        }
       //根据车辆编号查出车辆信息
        if (StringUtils.isNotEmpty(faultReq.getVehicleCode())){
            QueryWrapper qw = new QueryWrapper();
            qw.eq("code",faultReq.getVehicleCode());
            BikeVehicle bikeVehicle = bikeVehicleMapper.selectOne(qw);
            if (bikeVehicle!=null){
                bikeFaultSubmit.setVehicleId(bikeVehicle.getId());
                BikeVehicle bv= new BikeVehicle();
                bv.setId(bikeVehicle.getId());
                bv.setStatus("5");
                bikeVehicleMapper.updateById(bv);
            }
        }
        if (StringUtils.isNotEmpty(faultReq.getPileCode())&&faultReq.getPileCode().length()!=11){
            return BikeResult.error("0","请填写正确车桩号",null);
        }
        if (StringUtils.isNotEmpty(faultReq.getPileCode())){
            //根据车桩编号查出车桩信息
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("code",faultReq.getPileCode().substring(5,7));
            queryWrapper.eq("station_id",bikeStation.getId());
            BikePile bikePile = bikePileMapper.selectOne(queryWrapper);
            if (bikePile!=null){
                bikeFaultSubmit.setPileId(bikePile.getId());
                BikePile bp=new BikePile();
                //改禁用
                bp.setPileStatus("0");
                bp.setId(bikePile.getId());
                bikePileMapper.updateById(bp);
            }
        }
        bikeFaultSubmit.setId(uuid);
        bikeFaultSubmit.setCode("GZ"+sdf.format(new Date()));
        bikeFaultSubmit.setStationId(bikeStation.getId());
        bikeFaultSubmit.setUserId(loginRes.getId());
        bikeFaultSubmit.setUserType("2");
        bikeFaultSubmit.setFaultType(faultReq.getFaultType()+"");
        bikeFaultSubmit.setContent(faultReq.getContent());
        bikeFaultSubmit.setIsDispatch(BikeConstant.y_n_no);
       int param = bikeFaultSubmitMapper.insert(bikeFaultSubmit);
       //保存图片地址
        if (faultReq.getBikeFaultFiles().size()>=1){
            List<BikeFaultSubmitFile>  fileList= faultReq.getBikeFaultFiles();
            for (BikeFaultSubmitFile fs:fileList) {
                BikeFaultSubmitFile bikeFaultSubmitFile = new BikeFaultSubmitFile();
                bikeFaultSubmitFile.setFaultId(uuid);
                bikeFaultSubmitFile.setFileUrl(fs.getFileUrl());
                bikeFaultSubmitFileMapper.insert(bikeFaultSubmitFile);
            }
        }
        if (param==1){
            //List<String> sysUserIds = bikeAnnouncementService.getSysUserIds(BikeConstant.sys_msg_report);
            //bikeAnnouncementService.addSysMsgByUser(sysUserIds,BikeConstant.sys_msg_report_text,loginRes.getUsername(),BikeConstant.sys_msg_report,uuid);
            return BikeResult.ok("1","上传故障成功！",param);
        }
        return BikeResult.error("0","上传故障失败",null);
    }

    @Override
    public BikeResult getStaffFaultList(Integer pageNum, Integer pageSize, HttpServletRequest request) {
        String accessToken = request.getHeader("X-Access-Token");
        // 解密获得username，用于和数据库进行对比
        String username = JwtUtil.getUsername(accessToken);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",username);
        LoginRes loginRes = staffMapper.selectOne(queryWrapper);

        Page<FaultRes> page = new Page<>(pageNum,pageSize);
        IPage<FaultRes> result= bikeFaultSubmitMapper.getStaffFaultList(page,loginRes.getId());
        List<FaultRes> records = result.getRecords();
        //排序
        records.sort(new Comparator<FaultRes>() {
            @Override
            public int compare(FaultRes o1, FaultRes o2) {
                return o2.getCreateTime().compareTo(o1.getCreateTime());
            }
        });
        //图片获取
        for (FaultRes submit:result.getRecords()) {
            QueryWrapper qw = new QueryWrapper();
            qw.eq("fault_id",submit.getId());
         List<BikeFaultSubmitFile> fileList = bikeFaultSubmitFileMapper.selectList(qw);

         if (fileList.size()!=0){
             fileList.forEach(
                     fl->{
                         fl.setFileUrl(domain+fl.getFileUrl());
                     }
             );
         }
            submit.setBikeFaultFiles(fileList);
        }
       return BikeResult.ok("1","查询成功！",result);
    }
}
